package com.ms.p2p.service.impl;


import com.ms.common.exception.NoticeException;
import com.ms.common.utils.AppContext;
import com.ms.common.utils.MsDateUtils;
import com.ms.common.utils.SpringContextHolder;
import com.ms.p2p.Constants;
import com.ms.p2p.bean.PageBean;
import com.ms.p2p.bean.Stay;
import com.ms.p2p.dao.LoanDao;
import com.ms.p2p.dao.LoanRepayDao;
import com.ms.p2p.entity.account.Account;
import com.ms.p2p.entity.loan.Loan;
import com.ms.p2p.entity.loan.LoanDueIn;
import com.ms.p2p.entity.loan.LoanStay;
import com.ms.p2p.entity.member.Member;
import com.ms.p2p.enums.AccountFLow;
import com.ms.p2p.enums.AccountType;
import com.ms.p2p.provider.*;
import com.ms.p2p.utils.impl.StayUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoanStayServiceImpl {




	@Autowired
	MemberServiceImpl memberService;
	@Autowired
	MemberAccountServiceImpl memberAccountService;
	@Autowired
	LoanServiceImpl loanService;

	@Autowired
	LoanDao loanDao;

	@Autowired
	LoanRepayDao loanRepayDao;
	@Autowired
	LoanTenderRecordServiceImpl loanTenderRecordService;
	@Autowired
	LoanDueInServiceImpl loanDueInService;
	@Autowired
	SendServiceImpl sendService;

	@Transactional(readOnly = false,propagation = Propagation.REQUIRED)
	public List<LoanDueIn> repay(String ip,Loan loan, LoanStay loanStay) {
		Account borrowerAccount = memberAccountService.findByUserId(loan.getUser_id());
		if (borrowerAccount.getBalance().compareTo(
				loanStay.getStay_account()) == -1) {
			throw  new NoticeException("账户余额不足，无法还款！");
		}
		loanStay.setStay_yesaccount(loanStay.getStay_account());
		loanStay.setStay_yestime(MsDateUtils.getTime());




		loan.setRepayment_yesaccount(loan.getRepayment_yesaccount().add(
				loanStay.getStay_account()));
		loan.setRepayment_yesinterest(loan.getRepayment_yesinterest().add(
				loanStay.getStay_interest()));
		List<LoanDueIn> dueIns = loanDueInService.findByBorrowIdAndOrder(loan.getId(), loanStay.getStay_periods());
		for(LoanDueIn dueIn:dueIns){
			if(dueIn.getDuein_status().equals(0)) {
				dueIn.setDuein_yestime(MsDateUtils.getTime());
				dueIn.setDuein_yesaccount(dueIn.getDuein_account());
				dueIn.setDuein_status(1);
				loanDueInService.update(dueIn);
				memberAccountService.OperAccount(ip, dueIn.getDuein_account(), dueIn.getDebt_user_id(), "标的<a  target='_blank' href='/bid/detail/" + loan.getId() + "'>【" + loan.getName() + "】</a>的第" + loanStay.getStay_periods() + "/" + loan.getRepayment_periods() + "期,待收减少￥" + dueIn.getDuein_account() + "。", AccountType.sub_col.getValue(), AccountFLow.FLOW_COL.getValue());
				memberAccountService.OperAccount(ip, dueIn.getDuein_account(), dueIn.getDebt_user_id(), "标的<a  target='_blank' href='/bid/detail/" + loan.getId() + "'>【" + loan.getName() + "】</a>的第" + loanStay.getStay_periods() + "/" + loan.getRepayment_periods() + "期还款￥" + dueIn.getDuein_account() + "。", AccountType.invest_repayment.getValue(), AccountFLow.FLOW_IN.getValue());
			}
		}
		if (loanStay.getStay_periods() == loan.getRepayment_periods()) {
			loan.setFinish_time(MsDateUtils.getTime());
			loan.setStatus(6);
		}
		loanService.update(loan);
		if (loan.getStay_periods() != loan.getRepayment_periods()) {
			loan.setStay_periods(loan.getStay_periods() + 1);
			Stay stay = StayUtil.getMoney(loan, loan.getStay_periods() - 1);
			stay.setOrder(loan.getStay_periods());
			loanDao.updateStay(stay, loan.getId());
		}else{
			Stay stay = new Stay();
			stay.setOrder(loan.getStay_periods());
			stay.setStay_account(BigDecimal.ZERO);
			stay.setStay_capital(BigDecimal.ZERO);
			stay.setStay_interest(BigDecimal.ZERO);
			loanDao.updateStay(stay, loan.getId());
		}

		if(loanStay.getStay_status()==0) {
			memberAccountService.OperAccount(ip, loanStay.getStay_account(), loan.getUser_id(), "标的<a   target='_blank' href='/bid/detail/" + loan.getId() + "'>【" + loan.getName() + "】</a>的第"
					+ loanStay.getStay_periods() + "/" + loan.getRepayment_periods()

					+ "的金额￥" + loanStay.getStay_account(), AccountType.repayment.getValue(), AccountFLow.FLOW_OUT.getValue());
		}
		loanStay.setStay_status(1);
		update(loanStay);

		return  dueIns;
	}



	/**
	 * 根据loan_id查询出下一次要还款的数据
	 *
	 * @param loan_id
	 * @return
	 */
	public LoanStay findNext(int loan_id) {
		return loanRepayDao.getNewxOrderByBorrowId(loan_id);

	}

	public int insert(LoanStay repay) {
		return loanRepayDao.insert(repay);
	}

	public int update(LoanStay repay) {
		return loanRepayDao.update(repay);

	}


	public List<Map<String,Object>> findPager(String userId, String userName, String borrowId, String status, String borrowName, String begin_date, String end_date, PageBean page) {
		return  loanRepayDao.findPager(userId,userName,borrowId,status,borrowName,begin_date,end_date,page.getBegin(),page.getPageSize());

	}

	public int findCount(String userId, String userName, String borrowId, String status, String borrowName, String begin_date, String end_date) {
		return loanRepayDao.findCount(userId,userName,borrowId,status,borrowName,begin_date,end_date);
	}


	public List<LoanStay> findList(Integer loanid) {
		return loanRepayDao.findList(loanid);
	}

}
